import { getUserInfo } from '@/api/user';
import router from '@/utils/router';
import { useConfigStore } from '@/stores/modules/configStore';
import { useAppStore } from '@/stores/modules/user';

export const useUser = () => {
  const configStore = useConfigStore();
  const appstore = useAppStore();
  const { routerConfig } = configStore;

  const getUserInfo = async () => {
    try {
      const res = await getUserInfo();
      console.log('------------>', res);
      if (res.data && res.data.user) {
        const { nickName, avatar, id } = res.data.user;
        appstore.actions.setUserInfo({ nickName, avatar, id });
        return res.data.user;
      } else {
        throw new Error('无效的响应结构');
      }
    } catch (error) {
      console.error('获取的用户数据失败', error);
      throw error;
    }
  };

  const isInvalidLogin = () => {
    if (appStore.getUserInfo.isLogin) {
      appStore.logout();
      const page = getCurrentPages().pop();
      const url = page.route;
      if (!configStore.routerConfig.whitelist.includes(url)) {
        setTimeout(() => {
          router.jump('/login');
        }, 3000);
      }
    }
  };

  return { getUserInfo, isInvalidLogin };
};
